package org.ponly.lpf4j.util.graph;

import java.util.*;

/**
 *  @author dsl
 */
public class CachingSemiGraph<Node> implements GraphGenerator.SemiGraph<Node> {
  private final Set<Node> myNodes;
  private final Map<Node, Set<Node>> myIn;

  public CachingSemiGraph(GraphGenerator.SemiGraph<Node> original) {
    myIn = new LinkedHashMap<Node, Set<Node>>();
    myNodes = new LinkedHashSet<Node>();
    for (final Node node1 : original.getNodes()) {
      myNodes.add(node1);
    }
    for (final Node node : myNodes) {
      final Set<Node> value = new LinkedHashSet<Node>();
      for (Iterator<Node> itin = original.getIn(node); itin.hasNext();) {
        value.add(itin.next());
      }
      myIn.put(node, value);
    }
  }

  public static <T> CachingSemiGraph<T> create(GraphGenerator.SemiGraph<T> original) {
    return new CachingSemiGraph<T>(original);
  }

  @Override
  public Collection<Node> getNodes() {
    return myNodes;
  }

  @Override
  public Iterator<Node> getIn(Node n) {
    return myIn.get(n).iterator();
  }
}